package com.study.shop.controller;

import com.study.shop.common.ShopException;
import com.study.shop.entity.common.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/admin/product")
public class FileController {


    @PostMapping("/fileUpload")
    public R<String> upload(MultipartFile file) throws IOException {
        System.out.println(file);
        URL resource = this.getClass().getClassLoader().getResource("static");
        if (resource == null) {
            throw new ShopException("目标路径不存在，文件上传失败");
        }
        LocalDate now = LocalDate.now();
        String date = now.format(DateTimeFormatter.ofPattern("/yyyy/MM/dd/"));
        String resPath = "/logo" + date + System.currentTimeMillis() + ".jpg";
        File f = new File(resource.getPath() + resPath);
        File parentFile = f.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        f.createNewFile();
        file.transferTo(f);
        return R.success(resPath);
    }
}
